primefaces/datatable.md at master · primefaces/primefaces · GitHub 您所在的位置:网站首页 datatable addrow primefaces/datatable.md at master · primefaces/primefaces · GitHub

primefaces/datatable.md at master · primefaces/primefaces · GitHub

#primefaces/datatable.md at master · primefaces/primefaces · GitHub| 来源: 网络整理| 查看: 265

DataTable

DataTable displays data in tabular format.

See this widget in the JavaScript API Docs.

Info Name Value Tag dataTable Component Class org.primefaces.component.datatable.DataTable Component Type org.primefaces.component.DataTable Component Family org.primefaces.component Renderer Type org.primefaces.component.DataTableRenderer Renderer Class org.primefaces.component.datatable.DataTableRenderer Attributes Name Default Type Description allowUnsorting false Boolean Defines whether columns are allowed to be unsorted. Default is false. ariaRowLabel null String Label to read by screen readers on checkbox selection. binding null Object An el expression that maps to a server side UIComponent instance in a backing bean cellEditMode eager String Defines the cell edit behavior, valid values are "eager" (default) and "lazy". cellSeparator null String Separator text to use in output mode of editable cells with multiple components. clientCache false Boolean Caches the next page asynchronously, default is false. currentPageReportTemplate null String Template of the currentPageReport UI. dataLocale null Object Locale to be used in features such as filtering and sorting, defaults to view locale. dir ltr String Defines text direction, valid values are ltr and rtl. disableContextMenuIfEmpty false Boolean Decides whether to disable context menu or not if a table has no records. disabledSelection false Boolean Disables row selection when true. Overrides p:column's disabledSelection attr. Example: var="xxx" disabledSelection="#{xxx.year > 1960}" disabledTextSelection true Boolean Disables text selection on row click. draggableColumns false Boolean Columns can be reordered with dragdrop when enabled. draggableRows false Boolean When enabled, rows can be reordered using dragdrop. draggableRowsFunction null MethodExpression Method expression to execute after dragging row. editInitEvent null String Defines a client side event to open cell on editable table. editMode row String Defines edit mode, valid values are row and cell. editable false Boolean Controls incell editing. editingRow false Boolean Defines if cell editors of row should be displayed as editable or not. emptyMessage No records found. String Text to display when there is no data to display. Alternative is emptyMessage facet. escapeText true Boolean Defines if headerText and footerText values on columns are escaped or not. Default is true. expandedRow false Boolean Defines if row should be rendered as expanded by default. filterBy null FilterMeta / Collection Property to be used for default filtering. Expects a single or a collection of FilterMeta. filterDelay 300 Integer Delay in milliseconds before sending an ajax filter query. filterEvent keyup String Event triggering filter for input filters. filteredValue null List List to keep filtered data. first 0 Integer Index of the first row to be displayed frozenColumns 0 Integer Number of columns to freeze from start index 0. frozenRows null Object Collection to display as fixed in scrollable mode. globalFilter null String Value of the global filter to use when filtering by default. globalFilterOnly false Boolean When true this will hide all column filters and allow all columns to be filtered by global filter only. globalFilterFunction null MethodExpression Custom implementation to globally filter a value against a constraint. id null String Unique identifier of the component lazy false Boolean Controls lazy loading. In most cases this is detected automatically based on value-binding to LazyDataModel. So no need to set this explicit. liveResize false Boolean Columns are resized live in this mode without using a resize helper. liveScroll false Boolean Enables live scrolling. liveScrollBuffer 0 Integer Percentage height of the buffer between the bottom of the page and the scroll position to initiate the load for the new chunk. Value is defined in integer and default is 0. multiViewState false Boolean Whether to keep table state across views, defaults to false. nativeElements false Boolean Uses native radio-checkbox elements for row selection. onExpandStart null String Client side callback to execute before expansion. onRowClick null String Client side callback to execute after clicking row. pageLinks 10 Integer Maximum number of page links to display. paginator false Boolean Enables pagination. paginatorAlwaysVisible true Boolean Defines if paginator should be hidden if total data count is less than number of rows per page. paginatorPosition both String Position of the paginator. paginatorTemplate null String Template of the paginator. reflow false Boolean Reflow mode is a responsive mode to display columns as stacked depending on screen size. rendered true Boolean Boolean value to specify the rendering of the component, when set to false component will not be rendered. renderEmptyFacets false Boolean Render facets even if their children are not rendered. Default is false. See #4840 resizableColumns false Boolean Enables column resizing. resizeMode fit String Defines the resize behavior, valid values are "fit" (default) and expand. rowDragSelector td,span:not(.ui-c) String Defines the element used to reorder rows using dragdrop. Default selector is "td,span:not(.ui-c)" rowEditMode eager String Defines the row edit behavior, valid values are "eager" (default) and "lazy". rowExpandMode new String Defines row expand mode, valid values are "single" and "multiple" (default). rowHover false Boolean Adds hover effect to rows, default is false. Hover is always on when selection is enabled. rowIndexVar null String Name of iterator to refer each row index. rowKey null String Unique identifier of a row. Must be defined when using selection together with non-lazy datasource (eg value-attribute bound to a instance of java.util.List). rowSelectMode new String Defines row selection mode for multiple selection. Valid values are "new", "add" and "checkbox". rowSelector null String Client side check if rowclick triggered row click event not a clickable element in row content. rowStatePreserved false Boolean Keeps state of its children on a per-row basis. Default is false. rowStyleClass null String Style class for each row. rows null Integer Number of rows to display per page. rowsPerPageLabel null String Label for the rowsPerPage dropdown. rowsPerPageTemplate null String Template of the rowsPerPage dropdown. saveOnCellBlur true Boolean Saves the changes in cell editing on blur, when set to false changes are discarded. scrollHeight null Integer Scroll viewport height. scrollRows 0 Integer Number of rows to load on live scroll. scrollWidth null Integer Scroll viewport width. scrollable false Boolean Makes data scrollable with fixed header. selection null Object Reference to the selection data. selectionMode null String Enables row selection, valid values are “single" and “multiple". selectionPageOnly true Boolean When using a paginator and selection mode is checkbox, the select all checkbox in the header will select all rows on the current page if true, or all rows on all pages if false. Default is true. showGridlines false Boolean When enabled, cell borders are displayed. size regular String Size of the table content, valid values are "small" and "large". Leave empty for regular size. sortMode multiple String Defines sorting mode, valid values are single and multiple. sortBy null SortMeta / Collection Property to be used for default sorting. Expects a single or a collection of SortMeta. skipChildren false Boolean Ignores processing of children during lifecycle, improves performance if table only has output components. stickyHeader false Boolean Sticky header stays in window viewport during scrolling. stickyTopAt null String Selector to position on the page according to other fixing elements on the top of the table. Default is null. stripedRows false Boolean Whether to display striped rows to visually separate content. style null String Inline style of the component. styleClass null String Style class of the component. summary null String Summary attribute for WCAG. tabindex null String Position of the element in the tabbing order. tableStyle null String Inline style of the table element. tableStyleClass null String Style class of the table element. value null Object Data to display. var null String Name of the request-scoped variable used to refer each data. virtualScroll false Boolean Loads data on demand as the scrollbar gets close to the bottom. Default is false. widgetVar null String Name of the client side widget. touchable false Boolean Enable touch support if browser detection supports it. Default is false because it is globally enabled by default. partialUpdate true Boolean When disabled, it updates the whole table instead of updating a specific field such as body element in the client requests of the dataTable. Getting started with the DataTable

We will be using the same Car and CarBean classes described in DataGrid section. Here is the simplest way to get started:

In case no children are present in columns, value from var and field will be displayed.

Header and Footer

Both datatable itself and columns can have custom content in their headers and footers using header and footer facets respectively. Alternatively for columns there are headerText and footerText shortcuts to display simple texts.

List of Cars Model #{car.model} 8 digit code #{car.year} //more columns In total there are #{fn:length(carBean.cars)} cars. Pagination

DataTable has a built-in ajax based paginator that is enabled by setting paginator option to true, see pagination section in dataGrid documentation for more information about customization options.

//columns

Optionally enabling clientCache property loads the next page asynchronously so that when user clicks the second page, data is displayed instantly from client side.

Paginator Template

Paginator is customized using paginatorTemplate attribute accepting various keys of UI controls.

FirstPageLink LastPageLink PreviousPageLink NextPageLink PageLinks CurrentPageReport RowsPerPageDropdown JumpToPageDropdown JumpToPageInput

Note that {RowsPerPageDropdown} has its own template, options to display is provided via rowsPerPageTemplate attribute (e.g. rowsPerPageTemplate="9,12,15").

Also {CurrentPageReport} has it's own template defined with currentPageReportTemplate option. You can use {currentPage},{totalPages},{totalRecords},{startRecord},{endRecord} keyword within currentPageReportTemplate. Default is "{currentPage} of {totalPages}". Default UI is:

which corresponds to the following template.

{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}

Here are more examples based on different templates;

{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}

{PreviousPageLink} {CurrentPageReport} {NextPageLink}

Paginator Position

Paginator can be positoned using paginatorPosition attribute in three different locations, "top", "bottom" or "both" (default).

Custom Content in Paginator

Custom content can be placed inside a paginator using a facet name matching a token in the template.

//Any content here //... Sorting

Defining field or sortBy attribute enables ajax based sorting on that particular column. Sorting cycles through ascending, descending and unsorted upon clicking on the column header.

Instead of using the default sorting algorithm which uses a java comparator, you can plug-in your own sort method as well.

public int sortByModel(Object car1, Object car2) { //return -1, 0 , 1 if car1 is less than, equal to or greater than car2 } ...more columns

Multiple sorting is enabled by default. In this mode, clicking a sort column while metakey is on adds sort column to the order group. Change attribute sortMode to single to allow only one column.

//columns

DataTable can display data sorted by default, by either setting default attributes on p:column or using sortBy attribute of datatable. Table below would be initially displayed as sorted by model.

Or

Filtering

Ajax based filtering is enabled by setting field or filterBy at column level and providing a list to keep the filtered sublist. It is suggested to use a scope longer than request like viewscope to keep the filteredValue so that filtered list is still accessible after filtering. (Attention: Please be aware sessionscope is not supported for this. Instead set multiViewState="true" to keep table state including filter across views.)

...more columns

Filtering is triggered with keyup event and filter inputs can be styled using filterStyle , filterStyleClass attributes. If you’d like to use a dropdown instead of an input field to only allow predefined filter values use filterOptions attribute and a collection/array of selectitems as value. In addition, filterMatchMode defines the built-in matcher which is startsWith by default.

Following is a basic filtering datatable with these options demonstrated:

Filter located at header is a global one applying on all fields, this is implemented by calling client side API method called filter(), important part is to specify the id of the input text as globalFilter which is a reserved identifier for datatable.

In addition to default filtering with generated elements, custom elements can also be used as a filter facet. Example below uses custom filter components in combination with generated elements. When a custom component is used as a filter facet, filtering needs to be called manually from a preferred event such as onchange="PF('carsTable').filter()". Also defining a converter might be necessary if the value of the filter facet is not defined.

Please make sure that the filter is using the same type as the column field if you are using comparable filter match modes (like greater than). For example, if the column field is an integer, and you would like to add a greater than filter, make sure to convert the filter to integer as well. Do so by adding a f:converter (see example below).

filterMatchMode defines which built-in filtering algorithm would be used per column, valid values for this attribute are;

startsWith : Checks if column value starts with the filter value. endsWith : Checks if column value ends with the filter value. contains : Checks if column value contains the filter value. exact : Checks if string representations of column value and filter value are same. lt : Checks if column value is less than the filter value. lte : Checks if column value is less than or equals the filter value. gt : Checks if column value is greater than the filter value. gte : Checks if column value is greater than or equals the filter value. equals : Checks if column value equals the filter value. in : Checks if column value is in the collection of the filter value. range : Checks if column value is within a provided range (p:datePicker offers this functionality)

In case the built-in methods do not suffice, custom filtering can be implemented using filterFunction approach.

filterFunction should be a method with three parameters; column value, filter value and locale. Return value is a boolean, true accepts the value and false rejects it.

public boolean filterByPrice(Object value, Object filter, Locale locale) { //return true or false }

Locale is provided as optional in case you need to use a locale aware method like toLowerCase(Locale locale). Note that | String | based filters like startsWith, endsWith uses toLowerCase already and dataLocale attribute is used to provide the locale to use when filtering.

This same principle can be applied globally by implementing a globalFilterFunction. It takes the same parameters of which the first parameter is the row value.

Default filtering can be set up with markup or programmatically. Here is two ways to go about it:

Or using DataTable#filterBy and FilterMeta#builder:

@PostConstruct public void init() { filterBy = new ArrayList(); filterBy.add(FilterMeta.builder() .field("year") .filterValue(20) .matchMode(MatchMode.CONTAINS) .build()); } Row Selection

There are several ways to select row(s) from datatable. Let’s begin by adding a Car reference for single selection and a Car array for multiple selection to the CarBean to hold the selected data.

public class CarBean { private List cars; private Car selectedCar; private List selectedCars; public CarBean() { cars = new ArrayList(); //populate cars } //getters and setters } Single Selection with a Command Component

This method is implemented with a command component such as commandLink or commandButton. Selected row can be set to a server side instance by passing as a parameter if you are using EL 2.2 or using f:setPropertyActionListener.

...columns Single Selection with Row Click

Previous method works when the button is clicked, if you’d like to enable selection wherever the row is clicked, use selectionMode option.

...columns Multiple Selection with Row Click

Multiple row selection is similar to single selection but selection should reference an array or a list of the domain object displayed and user needs to use press modifier key(e.g. ctrl) during selection *.

...columns Single Selection with RadioButton

Selection a row with a radio button placed on each row is a common case, datatable has built-in support for this method so that you don’t need to deal with h:selectOneRadios and low level bits. In order to enable this feature, define a column with selectionMode set as single.

...columns Multiple Selection with Checkboxes

Similar to how radio buttons are enabled, define a selection column with a multiple selectionMode. DataTable will also provide a selectAll checkbox at column header.

...columns

Tip: Use rowSelectMode option to customize the default behavior on row click of a multiple selection enabled datatable. Default value is "new" that clears previous selections, "add" mode keeps previous selections same as selecting a row with mouse click when metakey is on and "checkbox" mode allows row selection with checkboxes only.

RowKey

RowKey should a unique identifier from your data model and used by datatable to find the selected rows. You must define this key by using the rowKey attribute.

!> RowKey must not contain a comma , as it will break row selection. See GitHub #8932.

Dynamic Columns

Dynamic columns is handy in case you can’t know how many columns to render. Columns component is used to define the columns programmatically. It requires a collection as the value, two iterator variables called var and columnIndexVar.

public class CarBean { private List columns = new ArrayList(); private List cars; public CarBean() { populateColumns(); cars = //populate cars; } public void populateColumns() { String[] columnKeys = new String[]{"model","year","color"}; for(String columnKey : columnKeys) { columns.add(new ColumnModel(columnKey.toUpperCase(), columnKey)); } } //getters and setters static public class ColumnModel implements Serializable { private String header; private String property; public ColumnModel(String header, String property) { this.header = header; this.property = property; } public String getHeader() { return header; } public String getProperty() { return property; } } } Column Grouping

Grouping is defined by ColumnGroup component used to combine datatable header and footers.

#{sale.manufacturer} #{sale.lastYearProfit}% #{sale.thisYearProfit}% #{sale.lastYearSale}$ #{sale.thisYearSale}$ public class CarBean { private List sales; public CarBean() { sales = //create a list of BrandSale objects } public List getSales() { return this.sales; } }

For frozen columns, use frozenHeader , frozenFooter , scrollableHeader and scrollableFooter types.

Row Grouping

Rows can be grouped in two ways, using headerRow, summaryRow components or with groupRow attribute on a column.

!> Row Grouping does not work with Lazy Loading and LiveScroll as the grouping needs to know about all rows to properly group the rows.

Optionally rows can be made toggleable using HeaderRow#expandable property.

Alternative approach is using row spans where a row can group multiple rows within the same group. To enable this method, set groupRow to true on the grouping column.

Scrolling

Scrolling makes the header-footer of the table fixed and the body part scrollable. Scrolling is enabled using scrollable property and has 3 modes; x, y and x-y scrolling that are defined by scrollHeight and scrollWidth. These two scroll attributes can be specified using integer values indicating fixed pixels or percentages relative to the container dimensions.

//columns

Simple scrolling renders all data to client whereas virtual scrolling combined with lazy loading is useful to deal with huge data, in this case data is fetched on-demand. Set virtualScroll to enable this option and provide LazyDataModel;

//columns Frozen Rows

Certain rows can be fixed in a scrollable table by using the frozenRows attribute that defines the number of rows to freeze from the start.

//columns Frozen Columns

Specific columns can be fixed while the rest of them remain as scrollable. frozenColumns defines the number of columns to freeze from the start.

//columns Expandable Rows

RowToggler and RowExpansion facets are used to implement expandable rows.

Expand rows to see detailed information //columns //Detailed content of a car

p:rowToggler component places an expand/collapse icon, clicking on a collapsed row loads expanded content with ajax. If you need to display a row as expanded by default, use expandedRow attribute which is evaluated before rendering of each row so value expressions are supported. Additionally, rowExpandMode attribute defines if multiple rows can be expanded at the same time or not, valid values are "single" and "multiple" (default).

Editing

Incell editing provides an easy way to display editable data. p:cellEditor is used to define the cell editor of a particular column. There are two types of editing, row and cell. Row editing is the default mode and used by adding a p:rowEditor component as row controls.

In-Cell Editing //more columns with cell editors

When pencil icon is clicked, row is displayed in editable mode meaning input facets are displayed and output facets are hidden. Clicking tick icon only saves that particular row and cancel icon reverts the changes, both options are implemented with ajax interaction.

Another option for incell editing is cell editing, in this mode a cell switches to edit mode when it is clicked, losing focus triggers an ajax event to save the change value.

Lazy Loading

Lazy Loading is an approach to deal with huge datasets efficiently, regular AJAX based pagination works by rendering only a particular page but still requires all data to be loaded into memory. Lazy loading DataTable renders a particular page similarly but also only loads the page data into memory not the whole dataset. In order to implement this, you’d need to bind a org.primefaces.model.LazyDataModel as the value and implement load and count method. If you have selection enabled, you either need to implement getRowData and getRowKey, or pass a existing JSF Converter to the constructor.

//columns public class CarBean { private LazyDataModel model; public CarBean() { model = new LazyDataModel() { @Override public int count(Map filterBy) { // logical row count based on a count query taking filter into account return totalElements; } @Override public List load(int first, int pageSize, Map sortBy, Map filterBy) { // load physical data return requestedResultPage; } }; } public LazyDataModel getModel() { return model; } }

DataTable calls your load implementation whenever a paging, sorting or filtering occurs with following parameters:

first: Offset of first data to start from pageSize: Number of data to load sortBy: Active sorters map (field as key) filterBy: Active filters map (field as key).

In addition to load method, count method needs to be implemented, so that paginator can display itself according to the logical number of rows to display.

It is suggested to use field attribute of column component to define the field names passed as sortBy and filterBy, otherwise these fields would be tried to get extracted from the value expression which is not possible in cases like composite components.

To avoid doing a separate count-statement against your datasource you may implement it like this: (This may help to improve performance but comes at the price of keeping an eye on #1921.)

public class CarBean { private LazyDataModel model; public CarBean() { model = new LazyDataModel() { @Override public int count(Map filterBy) { return 0; } @Override public List load(int first, int pageSize, Map sortBy, Map filterBy) { //load physical data - your datasource (eg Spring Data or Apache Solr) has one API-call which returns page including rowCount org.springframework.data.domain.Page requestedResultPage = carRepository.find...; // afterwards set rowCount setRowCount(requestedResultPage.getTotalElements()); // return page data return requestedResultPage.getContent(); } }; } public LazyDataModel getModel() { return model; } }

A third variant may be doing something like this:

public class CarBean { private LazyDataModel model; public CarBean() { model = new LazyDataModel() { @Override public int count(Map filterBy) { return 0; } @Override public List load(int first, int pageSize, Map sortBy, Map filterBy) { // setRowCount and recalculateFirst is required if #count method isnt implemented correctly setRowCount(x); first = recalculateFirst(first, pageSize, getRowCount()); // load physical data return requestedResultPage; } }; } public LazyDataModel getModel() { return model; } } JpaLazyDataModel

PrimeFaces provides a OOTB implementation for JPA users, which supports basic features.

new JpaLazyDataModel(MyEntity.class, () -> entityManager);

If you have selection enabled, you can either pass the rowKey field name in the constructor:

new JpaLazyDataModel(MyEntity.class, () -> entityManager, "id");

or provide a existing JSF Converter:

new JpaLazyDataModel(MyEntity.class, () -> entityManager, myConverter);

Also you can add global filters via:



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有